﻿using ER.Dynamic;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data.Entity;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Hosting;

namespace ER.Tests.Data
{
    public class RuntimeDbContextManager
    {
        const string DbContextBuilderKey = "DbContextBuilderKey";
        const string ConnectionStringKey = "ConnectionName";
        const string CheckCodeFirstAutoMigrateKey = "IsAutoMigration";
        static readonly IDbContextBuilder dbContextBuilder = null;
        static object locker = new object();
        static RuntimeDbContextManager()
        {
            //if (File.Exists(HostingEnvironment.ApplicationPhysicalPath + @"Bin\" + Emiter.DynamicDllName) == false)
            {
                lock (locker)
                {
                    //if (File.Exists(HostingEnvironment.ApplicationPhysicalPath + @"Bin\" + Emiter.DynamicDllName) == false)
                    {
                        var builderType = ConfigurationManager.AppSettings[DbContextBuilderKey];
                        Type type = Type.GetType(builderType);
                        dbContextBuilder = Activator.CreateInstance(type) as IDbContextBuilder;
                        dbContextBuilder.Build();
                        if (ConfigurationManager.AppSettings[CheckCodeFirstAutoMigrateKey] != "true")
                        {
                            typeof(Database).GetMethod("SetInitializer").MakeGenericMethod(dbContextBuilder.TypeDbContextEmiter.Type).Invoke(null, new Object[] { null });
                        }
                    }
                }
            }
        }
        public static DbContext CreateDbContext()
        {
            string connectString = ConfigurationManager.ConnectionStrings[ConfigurationManager.AppSettings[ConnectionStringKey]].ConnectionString;
            return (dynamic)dbContextBuilder.CreateDbContext(connectString);
        }
    }
}